import "./index.less";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
import { messageGetList, messageDelete, messageModifyShow } from "@/api/modules/message";
import type { MessageGetListSendModel, MessageGetListReturnData } from "@/api/modules/message";
import { useState, useEffect } from "react";
import { Radio, Form, Button, Table, Row, Col, Tooltip, Switch, Space, Tag, Modal, Input, message, Popconfirm } from "antd";
import { SearchOutlined, PlusOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
const { TextArea } = Input;
const noticeAdmin = () => {
	const [loading, setLoading] = useState<boolean>(false);
	const [form] = Form.useForm();
	// 获取系统公告数据
	const [listQuerySystem, setListQuerySystem] = useState<MessageGetListSendModel>({
		page: 1,
		size: 5,
		type: "system",
		total: 0
	});
	const [messageSystemData, setMessageSystemData] = useState<MessageGetListReturnData[]>([]);
	function getMessageSystemGetList(listQuery: MessageGetListSendModel) {
		return new Promise(resolve => {
			messageGetList(listQuery)
				.then(({ data, code }) => {
					if (code === 0) {
						setMessageSystemData(data!.list);
						setListQuerySystem({ ...listQuery, total: data!.total });
					}
				})
				.finally(() => {
					resolve("");
				});
		});
	}
	// 获取店铺公告数据
	const [messageShopData, setMessageShopData] = useState<MessageGetListReturnData[]>([]);
	const [listQueryShop, setListQueryShop] = useState<MessageGetListSendModel>({
		page: 1,
		size: 5,
		type: "shop",
		total: 0
	});
	function getMessageShopGetList(listQuery: MessageGetListSendModel) {
		return new Promise(resolve => {
			messageGetList(listQuery)
				.then(({ data, code }) => {
					if (code === 0) {
						setMessageShopData(data!.list);
						setListQueryShop({ ...listQuery, total: data!.total });
					}
				})
				.finally(() => resolve(""));
		});
	}
	// 新增公告
	interface DialogModel {
		visible: boolean;
		title: string;
		type: string;
		id: number;
		name: string;
		isShow: boolean;
		modelType: string;
	}
	const [dialog, setDialog] = useState<DialogModel>({
		visible: false,
		title: "", // 模态框标题
		type: "", // 通知类型
		id: 0,
		name: "",
		isShow: false,
		modelType: ""
	});
	const [confirmLoading, setConfirmLoading] = useState(false);
	function openDialog({ id, name, isShow, type }: MessageGetListReturnData, modelType: "add" | "modify") {
		setDialog(prev => ({
			...prev,
			visible: true,
			modelType,
			title: modelType === "modify" ? "编辑通知" : "添加新通知",
			id,
			name,
			isShow,
			type
		}));
		if (modelType === "modify") {
			// 修改的时候回显数据
			form.setFieldsValue({
				name,
				isShow,
				type
			});
		}
	}

	const handleOk = () => {
		form.submit();
	};
	const handleCancel = () => {
		closeModal();
	};
	// 清除弹窗
	function closeModal() {
		setDialog({
			visible: false,
			title: "", // 模态框标题
			type: "", // 通知类型
			id: 0,
			name: "",
			isShow: false,
			modelType: ""
		});
	}
	const onFinish = async (form: DialogModel) => {
		setConfirmLoading(true);
		const model: MessageGetListReturnData = {
			...form,
			id: dialog.id || 0
		};
		messageModifyShow(model)
			.then(({ code, msg }) => {
				if (code === 0) {
					message.success(msg);
					getTableList();
					closeModal();
				}
			})
			.finally(() => {
				setConfirmLoading(false);
			});
	};
	const onFinishFailed = (errorInfo: any) => {
		message.warning("请检查表单填写是否正确！");
		console.log("Failed:", errorInfo);
	};
	// 表格列
	const columns: any[] = [
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "15%",
			render: (createTime: number) => (
				<Tooltip placement="topLeft" title={dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}>
					{dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}
				</Tooltip>
			)
		},
		{
			title: "公告内容",
			dataIndex: "name",
			key: "name",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "30%",
			render: (name: string) => (
				<Tooltip placement="topLeft" title={name}>
					{name}
				</Tooltip>
			)
		},
		{
			title: "公告类型",
			dataIndex: "type",
			key: "type",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "15%",
			render: (type: string) => (
				<Tooltip placement="topLeft" title={type === "system" ? "系统通知" : "店铺通知"}>
					<Tag color={type === "system" ? "green" : "magenta"}>{type === "system" ? "系统通知" : "店铺通知"}</Tag>
				</Tooltip>
			)
		},
		{
			title: "是否显示",
			align: "center",
			key: "isShow",
			width: "10%",
			render: (_: any, record: any) => (
				<Switch
					checkedChildren="开启"
					unCheckedChildren="关闭"
					defaultChecked={record.isShow}
					onChange={checked => onIsShowChange(checked, record)}
				/>
			)
		},
		{
			title: "操作",
			align: "center",
			key: "action",
			width: "30%",
			render: (_: any, record: any) => (
				<div className="f-c-c">
					<Space wrap>
						<Button type="primary" onClick={() => openDialog(record, "modify")}>
							修改
						</Button>
						<Popconfirm title="确定执行该操作吗？" onConfirm={() => removeMessage(record)} okText="Yes" cancelText="No">
							<Button type="primary" danger>
								删除
							</Button>
						</Popconfirm>
					</Space>
				</div>
			)
		}
	];
	// 分页器变化回调
	function handleSystemTableChange(pagination: any, type: "system" | "shop") {
		const listQuery: MessageGetListSendModel = {
			page: pagination.current,
			size: pagination.pageSize,
			total: pagination.total,
			type
		};
		if (type === "shop") {
			setListQueryShop(listQuery);
			getMessageShopGetList(listQuery);
			return;
		}
		if (type === "system") {
			setListQuerySystem(listQuery);
			getMessageSystemGetList(listQuery);
			return;
		}
	}
	// 删除公告
	function removeMessage(record: MessageGetListReturnData) {
		messageDelete({ id: record.id }).then(({ code, msg }) => {
			if (code === 0) {
				message.success(msg);
				if (record.type === "system") getMessageSystemGetList(listQuerySystem);
				else getMessageShopGetList(listQueryShop);
			}
		});
	}
	// 是否显示控制
	function onIsShowChange(checked: boolean, record: MessageGetListReturnData) {
		messageModifyShow({
			...record,
			isShow: checked
		}).then(({ code, msg }) => {
			if (code === 0) {
				message.success(msg);
				if (record.type === "system") getMessageSystemGetList(listQuerySystem);
				else getMessageShopGetList(listQueryShop);
			}
		});
	}
	// 获取数据
	function getTableList() {
		// showFullScreenLoading();
		setLoading(true);
		Promise.all([getMessageSystemGetList(listQuerySystem), getMessageShopGetList(listQueryShop)]).then(() => {
			// tryHideFullScreenLoading();
			setLoading(false);
		});
	}
	useEffect(() => {
		getTableList();
	}, []);
	return (
		<div className="noticeAdmin">
			<div className="noticeAdmin__title flex items-center justify-between mb-10">
				<span className="text-18 font-bold">通知管理</span>
				<Space className="flex items-center">
					<Button icon={<PlusOutlined />} onClick={() => openDialog({} as MessageGetListReturnData, "add")}>
						新增通知
					</Button>
					<Button type="primary" icon={<SearchOutlined />} onClick={getTableList}>
						查询
					</Button>
				</Space>
			</div>
			<Row className="noticeAdmin__content" gutter={10}>
				<Col xs={24} sm={24} md={24} lg={24} xl={24} xxl={12}>
					<Table
						loading={loading}
						bordered={false}
						dataSource={messageSystemData}
						columns={columns}
						rowKey={record => record.id}
						pagination={{
							current: listQuerySystem.page, // 当前页码
							pageSize: listQuerySystem.size, // 每页条数
							total: listQuerySystem.total, // 数据总数
							showSizeChanger: true, // 显示每页条数切换器
							showQuickJumper: true // 显示快速跳转输入框
						}}
						onChange={pagination => handleSystemTableChange(pagination, "system")} // 分页变化回调
					/>
				</Col>
				<Col xs={24} sm={24} md={24} lg={24} xl={24} xxl={12}>
					<Table
						loading={loading}
						bordered={false}
						dataSource={messageShopData}
						columns={columns}
						rowKey={record => record.id}
						pagination={{
							current: listQueryShop.page, // 当前页码
							pageSize: listQueryShop.size, // 每页条数
							total: listQueryShop.total, // 数据总数
							showSizeChanger: true, // 显示每页条数切换器
							showQuickJumper: true // 显示快速跳转输入框
						}}
						onChange={pagination => handleSystemTableChange(pagination, "shop")} // 分页变化回调
					/>
				</Col>
			</Row>
			<Modal
				width={650}
				title={dialog.title}
				open={dialog.visible}
				destroyOnClose={true}
				onOk={handleOk}
				confirmLoading={confirmLoading}
				onCancel={handleCancel}
			>
				<Form form={form} preserve={false} size="middle" autoComplete="off" onFinish={onFinish} onFinishFailed={onFinishFailed}>
					<Form.Item label="通知内容" name="name" rules={[{ required: true, message: "请输入通知内容" }]}>
						<TextArea autoSize={{ minRows: 3 }} placeholder="输入通知内容" showCount={true} allowClear={true} />
					</Form.Item>
					<Form.Item label="是否显示" name="isShow" rules={[{ required: true, message: "请选择是否显示" }]}>
						<Switch defaultChecked={dialog.isShow} checkedChildren="开启" unCheckedChildren="关闭" />
					</Form.Item>
					<Form.Item label="公告类型" name="type" rules={[{ required: true, message: "请选择公告类型" }]}>
						<Radio.Group optionType="button" buttonStyle="solid">
							<Radio value="system">系统通知</Radio>
							<Radio value="shop">店铺通知</Radio>
						</Radio.Group>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
};

export default noticeAdmin;
